import { performanceMonitor, UnifiedPerformanceMonitor } from '../tests/unifiedPerformanceMonitor';

// 测试工具类
export class TestUtils {
  private static instance: TestUtils;
  private performanceMonitor: UnifiedPerformanceMonitor;

  constructor() {
    this.performanceMonitor = performanceMonitor;
  }

  static getInstance(): TestUtils {
    if (!TestUtils.instance) {
      TestUtils.instance = new TestUtils();
    }
    return TestUtils.instance;
  }

  // 开始性能测试
  startPerformanceTest() {
    console.log('🧪 开始性能测试...');
    this.performanceMonitor.enableRenderMonitoring();
    this.performanceMonitor.reset();
    return this.performanceMonitor;
  }

  // 结束性能测试并返回结果
  endPerformanceTest() {
    const metrics = this.performanceMonitor.getRenderMetrics();
    this.performanceMonitor.printRenderReport();
    console.log('🧪 性能测试结束');
    return metrics;
  }

  // 模拟表单操作序列
  async simulateFormOperations() {
    console.log('🎭 开始模拟表单操作...');

    // 模拟用户输入延迟
    const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

    // 这里可以添加具体的表单操作模拟
    // 由于需要实际的 DOM 操作，这里只是示例框架

    await delay(1000);
    console.log('🎭 表单操作模拟完成');
  }

  // 验证性能指标
  validatePerformanceMetrics(metrics: any, expectedOptimizationRate = 50) {
    const optimizationRate =
      metrics.renderCount + metrics.skippedRenders > 0
        ? (metrics.skippedRenders / (metrics.renderCount + metrics.skippedRenders)) * 100
        : 0;

    const isValid = optimizationRate >= expectedOptimizationRate;

    console.log(`📊 性能验证结果:`);
    console.log(`  - 优化率: ${optimizationRate.toFixed(2)}%`);
    console.log(`  - 期望值: >= ${expectedOptimizationRate}%`);
    console.log(`  - 验证结果: ${isValid ? '✅ 通过' : '❌ 失败'}`);

    return isValid;
  }

  // 生成测试报告
  generateTestReport(testResults: any) {
    console.group('📋 测试报告');
    console.log('测试时间:', new Date().toLocaleString());
    console.log('测试结果:', testResults);
    console.groupEnd();
  }
}

// 测试配置
export const TEST_CONFIG = {
  // 性能测试配置
  performance: {
    expectedOptimizationRate: 50, // 期望的优化率
    maxRenderTime: 5, // 最大渲染时间（ms）
    maxMemoryUsage: 50 // 最大内存使用（MB）
  },

  // 功能测试配置
  functional: {
    syncTimeout: 1000, // 同步超时时间（ms）
    effectTimeout: 2000 // Effect 执行超时时间（ms）
  },

  // UI 测试配置
  ui: {
    animationDuration: 300, // 动画持续时间（ms）
    interactionDelay: 100 // 交互延迟（ms）
  }
};

// 测试断言工具
export class TestAssertions {
  // 断言性能指标
  static assertPerformance(metrics: any, config: any = TEST_CONFIG.performance) {
    const optimizationRate =
      metrics.renderCount + metrics.skippedRenders > 0
        ? (metrics.skippedRenders / (metrics.renderCount + metrics.skippedRenders)) * 100
        : 0;

    const assertions = {
      optimizationRate: optimizationRate >= config.expectedOptimizationRate,
      renderTime: metrics.renderTime <= config.maxRenderTime * metrics.renderCount,
      renderCount: metrics.renderCount > 0,
      skippedRenders: metrics.skippedRenders >= 0
    };

    console.log('🔍 性能断言结果:', assertions);
    return assertions;
  }

  // 断言功能正确性
  static assertFunctionality(conditions: any) {
    const assertions = {
      syncWorking: conditions.syncWorking || false,
      effectsWorking: conditions.effectsWorking || false,
      dependenciesWorking: conditions.dependenciesWorking || false,
      groupsWorking: conditions.groupsWorking || false
    };

    console.log('🔍 功能断言结果:', assertions);
    return assertions;
  }

  // 断言用户体验
  static assertUserExperience(conditions: any) {
    const assertions = {
      responsive: conditions.responsive || false,
      smooth: conditions.smooth || false,
      intuitive: conditions.intuitive || false,
      accessible: conditions.accessible || false
    };

    console.log('🔍 用户体验断言结果:', assertions);
    return assertions;
  }
}

// 测试数据生成器
export class TestDataGenerator {
  // 生成标准测试操作序列
  static generateStandardOperations() {
    return [
      { field: 'employeeCount', value: 100, description: '修改员工数量' },
      { field: 'businessType', value: 'manufacturer', description: '选择生产制造商' },
      { field: 'industryType', value: 'textileAndClothing', description: '选择纺织服装' },
      { field: 'employeeCount', value: 200, description: '再次修改员工数量' },
      { field: 'businessType', value: 'distributor', description: '选择分销商' }
    ];
  }

  // 生成性能测试数据
  static generatePerformanceTestData() {
    return {
      baseline: {
        renderCount: 0,
        renderTime: 0,
        skippedRenders: 0
      },
      optimized: {
        renderCount: 0,
        renderTime: 0,
        skippedRenders: 0
      }
    };
  }
}

// 导出测试工具
export default TestUtils;
